const router = require('koa-router')()
const { exec } = require('../db')
const jwt = require('jsonwebtoken')
const {md5Pwd}=require('../utils/utility')

router.post('/login', async (ctx, next) => {
    let { username, password } = ctx.request.body
    let loginSql = `SELECT * FROM userlist WHERE username='${username}' AND password='${password}'`
    const data = await exec(loginSql)
    console.log(data)
    if (data.length > 0) {
        ctx.body = {
            code: 200,
            msg: '登陆成功',
            nickname: data[0].nickname,
            token: jwt.sign({ username: data[0].username }, '1906A')
        }
    } else {
        ctx.body = {
            code: 403,
            msg: '密码错误'
        }
    }
})
router.post('/register',async(ctx,next)=>{
    let { username, password,nickname } = ctx.request.body
    let regSql=`SELECT * FROM userlist WHERE username='${username}'`
    const regData=await exec(regSql)
    if(regData.length<=0){
        let addRegSql=`INSERT INTO userlist (username,password,nickname,id) VALUES ('${username}','${md5Pwd(password)}','${nickname}',NULL)`
        await exec(addRegSql)
        ctx.body={
            msg:'注册成功',
            code:200
        }
    }else{
        ctx.body={
            msg:'该用户已注册',
            code:303
        }
    }
})

module.exports = router
